# Only run the following scripts if jenkins_master is set
Setup jenkins user:
  user.present:
    - name: jenkins
    - gid_from_name: true
    - optional_groups:
      - lighttpd

Setup public key for jenkins master to access:
  ssh_auth.present:
    - user: jenkins
    - source: salt://jenkins/files/jenkins_master_public_key

Allow Jenkins to run salt-call:
  file.blockreplace:
    - name: /etc/sudoers
    - marker_start: "# START saltstack generated sudoer entries (for Jenkins)"
    - marker_end:   "# END   saltstack generated sudoer entries (for Jenkins)"
    - content:  |
        # Jenkins Salt-call SUDO SETTINGS
        Defaults:jenkins !requiretty
        jenkins ALL=NOPASSWD: /usr/bin/salt-call
    - append_if_not_found: True

Setup new node xml:
  file.managed:
    - name: /tmp/jenkin-node.xml
    - source: salt://jenkins/files/node.xml.jinja
    - template: jinja

Get jenkins-cli from Jenkins server:
  file.managed:
    - name: /tmp/jenkins-cli.jar
    - source: salt://jenkins/files/jenkins-cli.jar

Temporary copy ciuser_private_key:
  file.managed:
    - name: /tmp/ciuser_private_key
    - source: salt://jenkins/files/ciuser_private_key

Add the jenkins node:
  cmd.run:
    - name: >
        java -jar jenkins-cli.jar
        -i ciuser_private_key
        -s http://{{ salt['pillar.get']('jenkins:host', '') }}
        create-node "{{ salt['pillar.get']('jenkins:node_name', '') }}"
        < jenkin-node.xml

    - cwd: /tmp/

    - unless: >
        java -jar jenkins-cli.jar
        -i ciuser_private_key
        -s http://{{ salt['pillar.get']('jenkins:host', '') }}
        get-node "{{ salt['pillar.get']('jenkins:node_name', '') }}"
        && test $? -eq 0

Clean up tmp files:
  file.absent:
    - names:
      - /tmp/jenkin-node.xml
      - /tmp/ciuser_private_key

Prepare directory for Jenkins Deployment Path:
  file.directory:
    - name: /var/www/seekasia.com/
    - user: jenkins
    - group: jenkins
    - mode: 0775
    - makedirs: True
    - unless: test -d /var/www/seekasia.com
